﻿using ICSharpCode.TextEditor.Document;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;  

namespace ICSharpCode.TextEditor.Util
{
    public class ThreadSafeList<T> : IEnumerable, IDisposable where T: DrawLine
    {
        private static readonly object lockToken = new object();
        private List<T> collection = new List<T>(); //new BlockingCollection<T>();

        public object SynchRoot
        {
            get
            {
                return lockToken;
            }
        }

        public T this[int index]
        {
            get
            {
                lock (lockToken)
                {
                    return collection[index];
                }
            }
        }

        public void Dispose()
        {
            lock (lockToken)
            {
                collection.Clear();
                GC.Collect(1, GCCollectionMode.Optimized);
            }
        }

        public IEnumerator GetEnumerator()
        {
            lock (lockToken)
            {
                return collection.GetEnumerator();
            }
        }    

        public ThreadSafeList<T> CloneToList<S>() where S : T , new()
        {
            lock (lockToken)
            {
                ThreadSafeList<T> result = new ThreadSafeList<T>();
                foreach (T t in collection)
                {
                    S s = new S();
                    s.StartLocation = t.StartLocation;
                    s.EndLocation = t.EndLocation;
                    s.StartPoint = t.StartPoint;
                    s.EndPoint = t.EndPoint;
                    result.Add(s);
                }
                return result;
            }            
        }

        public void Add(T item)
        {
            lock (lockToken)
            {
                collection.Add(item);
            }
        }

        public void Clear()
        {
            lock (lockToken)
            {
                collection.Clear();
            }
        }

    }
}
